package 课程设计报告_hb_7_7;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.junit.Test;

/**
 * 通过对象的序列化和反序列化对象的复制
 * 
 * 只有通过对象的序列化和反序列化才能实现对象的深克隆
 * 
 * 通过Object#clone或者构造器的复制只能实现浅克隆
 * 
 * io采用装饰器的（设计模式）
 */


/**
 * @author Jiang Zhiyan
 *
 * 2021年7月7日 上午10:13:21
 *
 */
public class CloneTest {

	public Object copyObjByFile(Object src) {
		try(FileOutputStream fos = new FileOutputStream("./demo/temp.obj");
				ObjectOutputStream oos = new ObjectOutputStream(fos);){
			oos.writeObject(src);
			oos.flush();
			try(FileInputStream fis = new FileInputStream("./demo/temp.obj");
					ObjectInputStream ois = new ObjectInputStream(fis);){
				Object result = ois.readObject();
				return result;
			}
		}catch(Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	@Test
	public void copyList() {
		Student s1 = new Student ("小白","11","互联网");
		Student s2 = new Student ("小黑","23","互联网");
		Student s3 = new Student ("小小","19","互联网");
		
		List<Student> stus = new ArrayList<Student>();
		Collections.addAll(stus, s1,s2,s3);
		
		Object o1 = copyObjByFile(stus);
		if(o1 instanceof List) {
			List c1 = (List) o1;
			System.out.println(c1.get(1));
		}
		System.out.println(stus.get(1));
	}
	
	@Test
	public void cloneTest () throws CloneNotSupportedException{
		Student s1 = new Student ("小白","11","互联网");
		Student s2 = new Student ("小黑","23","互联网");
		Student s3 = new Student ("小小","19","互联网");
		
		List<Student> stus = new ArrayList<Student>();
		Collections.addAll(stus, s1,s2,s3);
		
		ArrayList<Student> copy = (ArrayList<Student>) stus.clone();
		System.out.println(stus);
		System.out.println(copy);
		System.out.println(stus.get(1));
		System.out.println(copy.get(1));
		
	}
}
